<template>
  <div>
    <el-dialog title="年审编辑" :visible.sync="dialogVisible" width="1400px" :close-on-click-modal="false">
      <div>
        <div class="card-title">不动产证信息</div>
        <el-form ref="ruleForm" :model="form" class="form-wrap" size="small">
          <el-form-item label="授权号">
            <el-input v-model="form.authorizationNumber" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="使用单位">
            <el-input v-model="form.unitName" disabled></el-input>
          </el-form-item>
          <el-form-item label="授权类型">
            <br />
            {{form.authorizationType | dict('authorization-type')}}
          </el-form-item>
          <el-form-item label="授权时间">
            <el-input v-model="form.authorizationTime" disabled></el-input>
          </el-form-item>
          <el-form-item label="超期天数">
            <el-input v-model="form.overdueTm" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注" class="full">
            <el-input v-model="form.remarks" disabled></el-input>
          </el-form-item>

          <el-form-item label="附件" class="col-two">
            <uploadMedia type="file" :url="url" :busId="form.useCardId" :modelType="modelType" ref="useCardFile" :isView="true" :autoLoadFiles="false" />
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="card-title">物业信息</div>
        <el-table :row-style="{height:'50px'}" :data="tableList" style="width: 100%" class="full box-item">
          <el-table-column type="index" width="55"></el-table-column>
          <el-table-column prop="propertyId" label="物业编号"></el-table-column>
          <el-table-column prop="propertyName" label="物业名称"></el-table-column>
          <el-table-column prop="addressArea" label="建筑面积"></el-table-column>
          <el-table-column prop="startTime" width="200" label="开始时间">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.startTime" type="datetime" value-format=" yyyy-MM-dd" format="yyyy-MM-dd" disabled></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column width="200" label="结束时间">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.endTime" type="datetime" value-format=" yyyy-MM-dd" format="yyyy-MM-dd" disabled></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="授权用途">
            <template slot-scope="scope">{{scope.row.authorizationUse| dict('authorization-use')}}</template>
          </el-table-column>
          <el-table-column label="实际用途">
            <template slot-scope="scope">{{scope.row.practicalUse| dict('practical-use')}}</template>
          </el-table-column>
          <el-table-column prop="useStatus" label="使用状态">
            <template slot-scope="scope">{{scope.row.useStatus| dict('use-status')}}</template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注"></el-table-column>
        </el-table>
      </div>
      <div class="box-item">
        <div class="data-title card-title">
          <span>年审信息</span>
          <span style="text-align: right;margin: 10px">
            <div>
              <el-button
                size="mini"
                round
                :icon="`el-icon-${status == '0' ? 'close':'check'}`"
                :type="status == '0' ? 'warning' : 'primary'"
              >年审{{status == '0' ? '不通过' : '通过'}}</el-button>
            </div>
          </span>
        </div>
        <el-tabs v-model="activeName" class="box-item">
          <el-tab-pane label="年审新增记录" name="first">
            <!--                        <div style="text-align: right;margin: 10px">-->
            <!--                            <el-button type="primary" size="small" @click="add">新增</el-button>-->
            <!--                        </div>-->

            <el-table :data="tableData" align="center" :span-method="objectSpanMethod">
              <el-table-column type="index" v-if="false"></el-table-column>
              <el-table-column align="center" label="年审日期">
                <template slot-scope="scope">
                  <span>{{scope.row.annualAuditTm}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="400" label="年审考核要求">
                <template slot-scope="scope">
                  <span>{{scope.row.auditContent}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="年审是否通过">
                <template slot-scope="scope">
                  <el-radio v-model="scope.row.annualStatus" label="0">是</el-radio>
                  <el-radio v-model="scope.row.annualStatus" label="1">否</el-radio>
                </template>
              </el-table-column>

              <el-table-column align="center" width="400" label="备注">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" maxlength="1000"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="年审历史记录" name="second">
            <el-table :data="tableData1" align="center">
              <el-table-column align="center" width="160px" label="年审日期">
                <template slot-scope="scope">
                  <span>{{scope.row.annualAuditTm}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="年审结果">
                <template slot-scope="scope">
                  <el-row class="resultWrap" type="flex">
                    <el-col :span="5">
                      <el-button size="mini" @click="updataISshow(scope.$index)">年审{{scope.row.annualResult=='0'?'不':''}}通过</el-button>
                    </el-col>
                    <el-col v-if="scope.row.Isshow">
                      <ul class="reasonList">
                        <li v-for="(item, index) in scope.row.recordList" :key="index">{{item.auditContent}}</li>
                      </ul>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="box-item" style="text-align: right;padding-top: 20px">
        <el-button type="primary" size="small" v-throttle="[submit]">保存</el-button>
        <el-button type="primary" size="small" @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUseCard } from '../../use-card/api/use-card'
import { fetchList } from '../../annual-audit-setting/api/annualaudittemplate'
import { addObj, getAnnualAuditInfoByUseCardId } from '../api/annualauditinfo'
import { getAnnualAuditRecord } from '../api/annualauditrecordhrs'
import uploadMedia from "~/components/upload-media.vue"
export default {
  components: { uploadMedia },

  data () {
    return {
      dialogVisible: false,
      isEdit: true,
      Isshow: false,
      url: '/admin/sys-file/upLodeFileEdit',
      fileUploadUrl: '/admin/sys-file/upLodeFileAdd',
      modelType: "use-card",
      status: '0',
      uploadFileList: [],
      authorizationPeriod: '',
      tableList: [],
      tableData: [],
      tableData1: [],
      form: {
        pastDate: 0,
        authorizationTime: ''
      },
      template: [],
      uploadStatus: false,
      activeName: 'first',
      myModel: 'annual'
    }
  },
  watch: {
    tableData: {
      handler (newVal, oldVal) {
        let num = 0;
        newVal.map(data => {
          num += parseInt(data.annualStatus)
        })
        if (num > 0) {
          this.status = '0'
        } else {
          this.status = '1'
        }
      },
      deep: true
    },
    tableData1: {
      handler (newVal, oldVal) {
        this.tableData1 = newVal
      },
      deep: true
    }

  },
  methods: {
    // onChange(file, fileList, index) {
    //     this.tableData[index].files.push(file)
    // },
    show (item) {
      this.dialogVisible = true
      this.form = item
      this.form.authorizationTm = this.strToDate(item.authorizationTime.substring(0, 12))//字段类类型不一样，后面统一后可以去掉substring
      fetchList().then(res => {
        let data = res.data.data.records
        this.template = data.filter(v => v.annualStatus == '1')
        this.add()
      })
      getUseCard(item.useCardId).then(res => {
        let data = res.data.data
        this.tableList = data.useCardPropertyList
      })
      getAnnualAuditInfoByUseCardId(item.useCardId).then(res => {
        this.tableData1 = res.data.data.map(item => ({ ...item, Isshow: false, recordList: [], }))
      })
      this.$nextTick(() => {
        this.$refs.useCardFile && this.$refs.useCardFile.getFiles(item.useCardId)
      })


    },
    updataISshow (index) {
      getAnnualAuditRecord(this.tableData1[index].annualAuditHrsId).then(res => {
        this.tableData1[index].recordList = res.data.data
        console.log(this.tableData1[index].recordList)
      })
      this.tableData1[index].Isshow = !this.tableData1[index].Isshow
      //item.Isshow=!item.Isshow
      //this.Isshow=!this.Isshow
    },
    //将yyyy-%M-%d转化成yyyy-MM-dd
    strToDate (str) {
      let newTime = str.split('-');
      let newDate = '';
      for (let i in newTime) {
        if (newTime[i] < 10) {
          newTime[i] = '0' + parseInt(newTime[i]);
        }
      }
      for (let i = 0; i < newTime.length; i++) {
        if (i == newTime.length - 1) {
          newDate += newTime[i]
        } else {
          newDate += newTime[i] + '-'
        }
      }
      return newDate;
    },

    getDate () {
      var date = new Date()
      return date.getFullYear() + '-' + ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
    },
    getDaysBetween (dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      var days = 0
      if (endDate > startDate) {
        days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      }
      // alert(days);
      return Math.floor(days);
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % this.template.length === 0) {
          return {
            rowspan: this.template.length,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    add () {
      for (let i = 0; i < this.template.length; i++) {
        let data = {
          auditTemplateId: this.template[i].auditTemplateId,
          auditContent: this.template[i].auditContent,
          // annualAuditTm: this.form.authorizationTime.substring(0,12),//字段类类型不一样，后面统一后可以去掉substring
          annualAuditTm: this.getDate(),
          useCardId: this.form.useCardId,
          annualStatus: '0',
          remarks: ''
        }
        this.tableData.push(data)
      }
    },
    del (item) {
      this.tableData.splice(item, 1)
    },
    submit () {
      if (this.form.authorizationStatus == '已发放') {
        this.form.authorizationStatus = '0'
      } else {
        this.form.authorizationStatus = '1'
      }
      addObj({ annualAuditInfo: Object.assign(this.form, { 'annualStatus': this.status, 'annualResult': this.status, 'annualAuditTm': this.tableData[0].annualAuditTm }), annualAuditRecords: this.tableData }).then(res => {
        this.restData()
        this.$message('保存成功')
        this.dialogVisible = false
        this.$emit("rest")
      })
      // let resp = []
      // let i = 0;
      // //遍历template或者tabledata，拿到里面的files，
      // // 上传，获取业务id，拿到业务id，添加到tabledata里。。。
      // this.tableData.forEach(data => {
      //     if (data.files.length > 0) {
      //         const f = new Promise(resolve => {
      //             const formData = new FormData()
      //             formData.append('file', data.files[0].raw)
      //             formData.append('module', 'annual')
      //             this.http.post(this.fileUploadUrl, formData).then(res => {
      //                 let resData = res.data.data
      //                 data.busId = resData
      //                 resolve();
      //             })
      //         })
      //         resp.push(f)
      //     }
      //     i++;
      // })
      // // 遍历上传完成，再最后提交
      // Promise.all(resp).then(() => {
      //     addObj(Object.assign(this.tableData)).then(res => {
      //         if (res) {
      //             this.restData()
      //             this.$message('保存成功')
      //             this.dialogVisible = false
      //             this.$emit("rest")
      //
      //         }
      //     })
      // })

    },
    showProperty (id) {
      this.restData()
      this.$refs.editProperty.show(id)

    },
    restData () {
      this.authorizationPeriod = ''
      this.form = {}
      this.tableList = []
      this.tableData = []
      this.tableData1 = []
    },
    close () {
      this.dialogVisible = false
      this.restData()
    },

  }
}
</script>

<style lang='scss' scoped>
@include data-title();
@include info-list(3);
@include formWrap(5);
.resultWrap {
  align-items: center;
  min-height: 40px;
}
.reasonList {
  padding: 4px 0;
  border-left: 1px solid #f2f2f2;
  li {
    padding: 5px 10px;
    border-bottom: 1px solid #f2f2f2;
    font-size: 13px;
    text-align: left;
    &:last-child {
      border-bottom: none;
    }
  }
}
.box-item {
  margin-top: 20px;
}
</style>
